package wsepForum.ui.jaxcent.states;

import java.util.Vector;

import jaxcent.HtmlDiv;
import jaxcent.HtmlElement;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;
import wsepForum.common.elements.AForumElement;
import wsepForum.common.elements.Message;
import wsepForum.common.elements.Topic;
import wsepForum.common.elements.User.UserType;
import wsepForum.domain.handlers.AUserHandler;
import wsepForum.persistance.exceptions.WrongElementIDException;
import wsepForum.ui.jaxcent.IXContext;
import wsepForum.ui.jaxcent.states.XEditor.ActionType;

/**
 * @author Oren
 *
 */
public class XTopic implements IXState {
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	private HtmlElement messagesArea;
	private HtmlElement topicTitle;
	private HtmlDiv xPost1;
	private HtmlDiv xPost2;
	private Topic topic;
	private IXContext context;

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public XTopic(final IXContext context, int topicId, int msgId) {
		this(context,topicId);
		try {
			this.context.getPage().navigate("#MSG"+msgId);
		} catch (Jaxception e) {/*ignore problem with navigation*/}
	}

	public XTopic(final IXContext context, int topicId) {
		this.context = context;
		construct();
		JaxcentPage page = context.getPage();
		this.topicTitle = new HtmlElement(page, "xtitle");
		this.messagesArea = new HtmlElement(page, "xmessages");
		this.xPost1 = new HtmlDiv(page,"xpost1") {
			public void onClick() {
				context.loadEditor(ActionType.NEW_MSG_ON_TOPIC, new Object[] { topic});
			}
		};
		this.xPost2 = new HtmlDiv(page,"xpost2") {
			public void onClick() {
				context.loadEditor(ActionType.NEW_MSG_ON_TOPIC, new Object[] { topic});
			}
		};
		if (loadContent(topicId)) {
			new HtmlElement(page,"xbacktosection") {
				public void onClick() {
					context.loadSection(topic.getParentID());
				}
			};
		}
	}

	/*****************************
	 * METHODS                   *
	 *****************************/
	public boolean loadContent(int topicId) {
		try {
			this.topic = this.context.getSession().getHandler().getTopic(topicId);
		} catch (WrongElementIDException e1) {
			this.context.getPage().showMessageDialog("Topic is not exist in the database, maybe deleted...");
			this.context.loadSection(0);
			return false;
		} catch (Exception e1) {
			this.context.getPage().showMessageDialog("Cannot load topic! "+e1.getMessage());
			this.context.loadSection(0);
			return false;
		}
		this.context.setSection(this.topic.getParentID(), null);
		setByUserType();
		Vector<Message> messages = topic.getAllMessages();
		StringBuffer messagesBuffer = new StringBuffer();
		int bgnum = 2;
		for (Message m : messages) {
			messagesBuffer.append(makeMessageItem(bgnum,m));
			bgnum = ((bgnum==1)?2:1);
		}
		try {
			topicTitle.setInnerHTML(topic.getHeadLine());
			this.messagesArea.setInnerHTML(messagesBuffer.toString());
			UserType userType = context.getUserType();
			if (userType != UserType.GUEST) {
				linkButtons(messages);
			}
			return true;
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot comunnicate with page fields!");
			this.context.loadSection(0);
			return false;
		} catch (Exception e) {
			this.context.getPage().showMessageDialog("failue in parsing topic data! :S\n"+e.getMessage());
			this.context.loadSection(0);
			return false;
		}
	}


	private void linkButtons (Vector<Message> messages) {
		try {
			HtmlElement editButton;
			HtmlElement deleteButton;
			HtmlElement quoteButton;
			int id;
			final AUserHandler handler = this.context.getSession().getHandler();

			for (int i=0;i<messages.size();i++) {
				final Message message = messages.elementAt(i);
				id = message.getElementID();
				quoteButton = new HtmlElement(this.context.getPage(),"QUT"+id){
					public void onClick() {
							context.loadEditor(ActionType.REPLY_MSG, new Object[] { topic, message});
					}
				};
				quoteButton.show();
				if (handler.editMessageAuthentication(message, this.topic.getParentID())) {
					editButton = new HtmlElement(this.context.getPage(),"EDT"+id){
						public void onClick() {
								context.loadEditor(ActionType.EDIT_MESSAGE, new Object[] { topic, message});
						}
					};
					editButton.show();
				}
				if (handler.deleteMessageAuthentication(message, this.topic.getParentID())) {
					final boolean isFirst = (i==0);
					deleteButton = new HtmlElement(this.context.getPage(),"DEL"+id){
						public void onClick() {
								try {
									boolean confirm = context.getPage().showConfirmDialog("Are you sure you want to delete this?");
									if (confirm) {
										AForumElement element = handler.deleteMessage(topic.getElementID(), message.getElementID());
										if (isFirst)
											context.loadSection(element.getElementID());
										else {
											HtmlDiv deletedMsg = new HtmlDiv(context.getPage(),"MSG"+message.getElementID());
											deletedMsg.setInnerHTML("<B>Message deleted successfuly.</B>");
										}
									}
								} catch (Jaxception e) {
									context.getPage().showMessageDialog("problem with changing items on page,\n"+e.getMessage());
								} catch (Exception e) {
									context.getPage().showMessageDialog("problem with deleting message from topic,\n"+e.getMessage());
								}
						}
					};
					deleteButton.show();
				}
			}
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot comunnicate with page fields!");
		} catch (Exception e) {
			this.context.getPage().showMessageDialog("failue in parsing topic data! :S\n"+e.getMessage());
		}
	}

	private String makeMessageItem(int bgnum, Message message) {
		int id = message.getElementID();

		String messageBody = message.getBody().replace("\n-------------\n", "<HR \\>");
		String messageAuthor = message.getUserName();
		if (messageAuthor==null)
			messageAuthor="guest";
		messageBody = messageBody.replace("\n", "<BR \\>");
		return
		"<div id=\"MSG"+id+"\" class=\"post bg"+bgnum+"\"><div class=\"inner\">"+
		"<span class=\"corners-top\"><span></span></span>"+
		"<div class=\"postbody\"><ul class=\"profile-icons\">"+
		"<li style=\"display: none;\" id=\"EDT"+id+"\" class=\"edit-icon\"><a title=\"Edit message\"><span>Edit message</span></a></li>"+
		"<li style=\"display: none;\" id=\"DEL"+id+"\" class=\"delete-icon\"><a title=\"Delete message\">"+
		"<span>Delete message</span></a></li>"+
		"<li style=\"display: none;\" id=\"QUT"+id+"\" class=\"quote-icon\"><a title=\"Quote message\"><span>Quote message</span></a></li></ul>"+
		"<h3 class=\"first\"><a href=\"#MSG"+id+"\">"+message.getHeadLine()+"</a></h3>"+
		"<p class=\"author\"><a><img src=\"/images/icon_post_target.gif\" width=\"11\" height=\"9\" alt=\"message\" title=\"message\" /></a>by <strong><a>"+messageAuthor+"</a></strong> at "+message.getTimeStamp()+"</p>"+
		"<div class=\"content\">"+messageBody+"</div>"+
		"</div><dl class=\"postprofile\"><dt>"+
		"<img src=\"./images/avatar.png\" width=\"64\" height=\"64\" alt=\"User's avatar\" /><br />"+
		"<a>"+messageAuthor+"</a></dt></dl>"+
		"<div class=\"back2top\"><a href=\"#wrap\" class=\"top\" title=\"Back to top\">Back to top</a></div>"+
		"<span class=\"corners-bottom\"><span></span></span></div></div>"+
		"<hr class=\"divider\" />";
	}

	private void construct() {
		this.context.setBody(
			"<h2><a id=\"xtitle\"></a></h2>"+
			"<p><a id=\"xbacktosection\" class=\"left-box right\" accesskey=\"r\">back to section</a></p>"+
			"<br /><div class=\"topic-actions\">"+
			"<div class=\"buttons\">"+
			"<div style=\"display: none;\" id=\"xpost1\" class=\"reply-icon\"><a title=\"Post reply\"><span></span>Post reply</a></div>"+
			"</div></div><div class=\"clear\"></div><div id=\"xmessages\"></div>"+
			"<div class=\"topic-actions\"><div class=\"buttons\">"+
			"<div style=\"display: none;\" id=\"xpost2\" class=\"reply-icon\"><a title=\"Post reply\"><span id=\"MSG-1\"></span>Post reply</a></div>"+
			"</div></div>");
	}

	@Override
	public StateType getType() {
		return StateType.TOPIC;
	}

	private void setByUserType() {
		UserType userType = context.getUserType();
		try {
			if (userType != UserType.GUEST) {
				xPost1.show();
				xPost2.show();
			}
			else
			{
				xPost1.hide();
				xPost2.hide();
			}
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("problem with manipulating page, please try reloading the page");
		}
	}

}
